package com.getword.service.impl;

import com.getword.domain.*;
import com.getword.mongodao.ArticleCollectRepository;
import com.getword.mongodao.ArticleRepository;
import com.getword.mongodao.ArticleZanRepository;
import com.getword.mongodao.OutlineDetailRepository;
import com.getword.service.ArticleService;
import com.getword.utils.SpringContextUtil;
import com.getword.web.model.ArticleCondition;
import com.getword.web.model.Result;
import com.getword.web.model.ResultCode;
import com.mongodb.BasicDBObject;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

@Service
//@Transactional(readOnly = false)
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private OutlineDetailRepository outlineDetailRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ArticleZanRepository articleZanRepository;
    @Autowired
    private ArticleCollectRepository articleCollectRepository;

    @Override
    public Result getArticlePage(Pageable page, Article article) {
        article.setDeleted(false);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true) //改变默认大小写忽略方式：忽略大小写
                .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains()); //采用“包含匹配”的方式查询
        Example<Article> example = Example.of(article, matcher);
        Page<Article> data = articleRepository.findAll(example, page);
        return Result.success(data, null);
    }

    @Override
    public Page<Article> getArticles(Pageable page, Article article) {
        article.setDeleted(false);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //采用“包含匹配”的方式查询
        Example<Article> example = Example.of(article, matcher);
        BasicDBObject fieldsObject = new BasicDBObject();
        fieldsObject.put("title", 1);
        fieldsObject.put("summary", 1);
        fieldsObject.put("releaseTime", 1);
        fieldsObject.put("outlineDetail", 1);
        fieldsObject.put("sentiment", 1);
        System.out.println(fieldsObject.toString());
        Page<Article> all = articleRepository.findAllPage(example, fieldsObject, page);
        return all;
    }

    @Override
    public Long getArticleCount(Pageable page, ArticleCondition condition) {
//        long count = articleDao.selectCount(page, condition);
        return null;
    }

    // 先判断是否已经点赞了（后台校验，防止前端攻击）
    @Override
    public Result zan(String articleId) {
        User user = SpringContextUtil.getLoginUser();
        // 判断该文章是否已经点赞了
        ArticleZan zan = articleZanRepository.findArticleZanByArticleIdAndUserId(articleId, user.getId());
        if (zan != null) {
            return Result.fail("该文章已经点赞了");
        }
        ArticleZan articleZan = new ArticleZan();
        articleZan.setArticleId(articleId);
        articleZan.setUserId(user.getId());
        ArticleZan save = articleZanRepository.save(articleZan);
        return Result.success(save);
    }

    @Override
    public Result saveArticle(Article article) {
        // 查询outlineDetail对象
        OutlineDetail outlineDetail = outlineDetailRepository.findOutlineDetailByOutlineIdAndNum(article.getOutlineDetail().getOutlineId(),
                article.getOutlineDetail().getNum());
        article.setOutlineDetail(outlineDetail);
        article.setDeleted(false);
        Article save = articleRepository.save(article);
        return Result.success(save);
    }

    @Override
    public Result getArticleById(String id) {
        Article article = articleRepository.findArticleById(id);
        if (article == null) {
            return Result.fail(ResultCode.PARAM_IS_INVALID.getCode(), "文章不存在", null);
        }
        return Result.success(article, null);
    }


    @Override
    public Result updateArticle(String html, String title, String articleId) {
        // 条件
        Criteria where = Criteria.where("id").is(articleId);
        Query query = Query.query(where);
        Update update = new Update();
        update.set("title", title);
        update.set("content", html);
        UpdateResult result = mongoTemplate.updateFirst(query, update, Article.class);
        System.out.println(result);
        if (result.getMatchedCount() == 0) {
            return Result.fail("文章不存在");
        }
        if (result.getModifiedCount() == 0) {
            return Result.fail("文章未作修改");
        }
        return Result.success(new HashMap<String, Object>() {{
            put("id", articleId);
        }});
    }

    @Override
    public Result deleteArticle(String id) {
        Criteria where = Criteria.where("id").is(id);
        Query query = Query.query(where);
        Update update = new Update();
        update.set("deleted", true);
        UpdateResult result = mongoTemplate.updateFirst(query, update, Article.class);

        if (result.getMatchedCount() == 0) {
            return Result.fail("文章不存在");
        }
        return Result.success(new HashMap<String, String>() {{
            put("id", id);
        }});
    }

    @Override
    public Result getZanState(String articleId) {
        User user = SpringContextUtil.getLoginUser();
        ArticleZan zan = articleZanRepository.findArticleZanByArticleIdAndUserId(articleId, user.getId());
        if (zan == null) {
            return Result.success(new HashMap<String, String>() {{
                put("zan", "0");
            }});
        }
        return Result.success(new HashMap<String, String>() {{
            put("zan", "1");
        }});
    }

    @Override
    public Result getCollectState(String articleId) {
        User user = SpringContextUtil.getLoginUser();
        ArticleCollect collect = articleCollectRepository.findArticleCollectByUserIdAndArticleId(user.getId(), articleId);
        String state = collect == null ? "0" : "1";
        return Result.success(state);
    }

    @Override
    public Result collect(String articleId) {
        User user = SpringContextUtil.getLoginUser();
        // 先判断是否已经收藏了
        ArticleCollect collect = articleCollectRepository.findArticleCollectByUserIdAndArticleId(user.getId(), articleId);
        if(collect!=null){
            return Result.fail("该文章已经收藏了");
        }
        ArticleCollect sCollect = new ArticleCollect();
        sCollect.setUserId(user.getId());
        sCollect.setArticleId(articleId);
        sCollect.setCollectTime(new Date());
        ArticleCollect save = articleCollectRepository.save(sCollect);
        return Result.success(save);
    }

    @Override
    public Result zanCount(String articleId) {
        Query query = Query.query(Criteria.where("articleId").is(articleId));
        long count = mongoTemplate.count(query, ArticleZan.class);
        return Result.success(count);
    }


}
